package net.roostertech.bta2dpfixer;

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;

public class DeviceListAdapter extends ArrayAdapter<BluetoothDevice> {

    private LayoutInflater mInflater;
	Context mContext;

	DeviceDAO mDao;
	public DeviceListAdapter(Context context) {
		super(context, 0);
		
		mContext = context;
	    mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	    mDao = DeviceDAO.getInstance(context.getApplicationContext());
	}

	@Override
	public View getView(int position, View v, ViewGroup parent) {
		if (v == null) {
			v = mInflater.inflate(R.layout.btdevice, parent, false);
		}
		
		final BluetoothDevice device = getItem(position);
		CheckBox a2dpCapable = (CheckBox) v.findViewById(R.id.a2dpCapable);
		boolean isA2DP = mDao.isA2DP(device.getName());
		a2dpCapable.setChecked(isA2DP);
		a2dpCapable.setText(device.getName());
		
		a2dpCapable.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				CheckBox check = (CheckBox) v;
				if (check.isChecked()) {
					mDao.markA2DP(check.getText().toString());
				} else {
					mDao.unmarkA2DP(check.getText().toString());
				}
				mDao.dump();

			}
		});
		return v;
	}
}
